package com.wash.car.web.config;

import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;
import cn.hutool.core.date.DateUnit;
import com.wash.car.web.config.context.UserInfo;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Configuration;

@Configuration
public class CacheConfiguration implements ApplicationRunner {

    private static long cacheTimeOut = DateUnit.MINUTE.getMillis() * 30;

    private static final TimedCache<String, UserInfo> USER_LOGIN_CACHE = CacheUtil.newTimedCache(cacheTimeOut);

    /**
     * 根据token获取登录信息
     *
     * @param token
     * @return
     */
    public static final UserInfo get(String token) {
        return USER_LOGIN_CACHE.get(token);
    }


    /**
     * 添加用户登录缓存
     *
     * @param token
     * @param userInfo
     */
    public static final void add(String token, UserInfo userInfo) {
        USER_LOGIN_CACHE.put(token, userInfo);
    }


    /**
     * 根据token删除登录信息
     *
     * @param token
     */
    public static final void del(String token) {
        USER_LOGIN_CACHE.remove(token);
    }


    /**
     * 启动 USER_LOGIN_CACHE 定期过期
     *
     * @param args
     * @throws Exception
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {
        CacheConfiguration.USER_LOGIN_CACHE.schedulePrune(cacheTimeOut);
    }


}
